const express = require('express');
const router = express.Router();
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient()

const upload = require('../multer/multer');
const { parseToken } = require('../utils/token');
const baseURL = process.env.BASE_URL

/* GET 通讯 listing. */

// 获取可以发送消息的用户列表
// 1. 关注
// 2. 有未读消息
router.get('/userList', upload.none(), async (req, res) => {
    const { userId } = req.query
    const token = req.headers.authorization.split(' ')[1]
    const tokenData = await parseToken(token)
    if (!tokenData) return res.status(401).send({ msg: '登录过期' })
    const { id, user } = tokenData
    if (userId !== id) return res.status(401).send({ msg: '错误的用户信息' })
    // 一种是订阅的
    // 一种是有人发消息过来的
    await prisma.$transaction([
        prisma.followUser.findMany({
            where: {
                followedId: userId
            },
            select: {
                followig: {
                    select: {
                        id: true,
                        name: true,
                        img: true,
                    }
                }
            }
        }),
        prisma.messageLog.findMany({
            where: {
                acceptId: id,
                deleteStatus: false,
            },
            select: {
                readStatus: true,
                content: true,
                send: {
                    select: {
                        id: true,
                        name: true,
                        img: true
                    }
                },
            },
            orderBy: {
                time: 'desc'
            }
        })
    ]).then(result => {
        const followList = result[0].map(user => {
            const { followig: { id, name, img } } = user
            let filePath = ''
            if (img) {
                filePath = `${baseURL}/${img.replace(/\\/g, '/')}`
            }
            return {
                id,
                name,
                img: filePath,
                lastLog: '',
                total: 0
            }
        })
        const totalArr = []
        const readList = result[1].map(user => {
            const { readStatus, content, send: { id, name, img } } = user
            let filePath = ''
            if (img) {
                filePath = `${baseURL}/${img.replace(/\\/g, '/')}`
            }
            if (readStatus === false) {
                totalArr.push(content)
            }
            return {
                id,
                name,
                img: filePath,
                lastLog: content,
                total: totalArr.length
            }
        })
        const uniqueData = [...followList, ...readList].reduce((acc, current) => {
            const user = acc.find(item => item.id === current.id)
            if (!user) {
                return acc.concat([current])
            } else {
                return acc
            }
        }, [])
        res.status(200).send(uniqueData)
    }).catch(err => {
        res.status(404).send({ msg: '获取数据错误' })
    }).finally(async () => prisma.$disconnect())

})

// 获取 历史记录
router.get('/msgLogs', upload.none(), async (req, res) => {
    const { userId, sendTo } = req.query
    await prisma.$transaction([
        prisma.messageLog.findMany({
            where: {
                OR: [
                    { sendId: userId, acceptId: sendTo },
                    { sendId: sendTo, acceptId: userId },
                ],
            },
            orderBy: {
                time: 'asc'
            }
        }),
        prisma.messageLog.updateMany({
            where: {
                OR: [
                    { sendId: userId, acceptId: sendTo },
                    { sendId: sendTo, acceptId: userId },
                ],
            },
            data: {
                readStatus: true
            }
        })
    ])
        .then(result => {
            const resultData = result[0].reduce((accLog, currLog) => {
                const key = currLog.time.toJSON()
                if (!accLog[key]) {
                    accLog[key] = {}
                }
                const { sendId, acceptId, content, time } = currLog
                accLog[key] = { id: sendId, acceptId, content, time } 
                return accLog
            }, {})
            res.status(200).send(resultData)
        })
        .catch(error => {
            return res.status(401).send({ msg: '获取数据失败' })
        })
        .finally(async () => prisma.$disconnect)
})


// 发送消息，并记录
router.post('/sendMsg', upload.none(), async (req, res) => {
    const { sendTo, content, sendId } = req.body
    await prisma.$transaction([
        prisma.messageLog.create({
            data: {
                sendId: sendId,
                content: content,
                acceptId: sendTo,
            }
        }),
        prisma.messageLog.findMany({
            where: {
                AND: [
                    { sendId: sendId, acceptId: sendTo },
                    { sendId: sendTo, acceptId: sendId }
                ]
            }
        })
    ])
        .then(result => {
            const { content, time, sendId: id, acceptId } = result[0]
            const returnData = { id, content, time, acceptId }
            res.status(200).send(returnData)
        })
        .catch(error => {
            return res.status(401).send({ msg: '发送失败' })
        })
        .finally(async () => prisma.$disconnect)
})

// 接收图像数据并返回链接数组
router.post('/imgToUrl', upload.any(), async (req, res) => {
    if (req.files) {
        const files = req.files.map(file => `${baseURL}/${file.path.replace(/\\/g, '/').replace('public/', '')}`)
        return res.status(200).send(files)
    }else {
        return res.status(403).send({msg: '发生了错误'})
    }
})





module.exports = router;
